"""
文件名: monitoring.py
描述: 性能监控和系统状态API路由

本模块包含以下主要功能：
1. 系统性能指标查询
2. 缓存状态监控
3. 数据库性能分析
4. API配额使用统计

依赖模块:
   - fastapi: Web框架路由
   - utils: 性能监控工具
   - core: 配置和日志模块

使用示例:
   >>> GET /monitoring/performance - 获取性能报告
   >>> GET /monitoring/cache - 获取缓存状态
   >>> GET /monitoring/database - 获取数据库分析

注意事项:
   - 监控端点可能包含敏感信息
   - 生产环境要限制访问权限
   - 监控数据要定期清理
   - 性能报告可能影响系统性能

作者: AI助手
创建日期: 2024-06-27
最后修改: 2024-06-27
版本: 1.0.0
"""

from typing import Dict, Any, Optional
from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi.security import HTTPBearer

from src.api.dependencies import get_current_user
from src.core.database import get_db
from src.core.logger import get_logger
from src.models.user import User
from src.utils.performance import performance_monitor, MemoryProfiler
from src.utils.cache import cache_manager, cache_health_check
from src.utils.rate_limiter import youtube_quota_manager
from src.utils.database_optimization import (
    query_optimizer, 
    index_analyzer, 
    pool_optimizer,
    analyze_database_performance
)

logger = get_logger(__name__)
security = HTTPBearer()

router = APIRouter()


def require_admin_access(current_user: User = Depends(get_current_user)):
    """检查管理员权限"""
    # 这里应该检查用户是否是管理员
    # 为了演示，我们假设第一个用户是管理员
    if not hasattr(current_user, 'is_admin') or not current_user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="需要管理员权限"
        )
    return current_user


@router.get("/health", summary="系统健康检查")
async def system_health_check() -> Dict[str, Any]:
    """
    系统整体健康检查
    
    Returns:
        Dict[str, Any]: 健康检查结果
    """
    try:
        # 缓存健康检查
        cache_health = await cache_health_check()
        
        # 内存使用检查
        memory_info = MemoryProfiler.get_memory_usage()
        memory_alert = MemoryProfiler.memory_alert_check()
        
        # 系统性能指标
        system_stats = performance_monitor.get_system_stats(minutes=10)
        
        # 整体健康状态
        overall_healthy = (
            cache_health.get("healthy", False) and
            not memory_alert and
            system_stats.get("avg_cpu_usage", 100) < 90
        )
        
        return {
            "healthy": overall_healthy,
            "timestamp": datetime.utcnow().isoformat(),
            "components": {
                "cache": {
                    "healthy": cache_health.get("healthy", False),
                    "stats": cache_health.get("stats", {})
                },
                "memory": {
                    "healthy": not memory_alert,
                    "usage": memory_info
                },
                "system": {
                    "healthy": system_stats.get("avg_cpu_usage", 100) < 90,
                    "stats": system_stats
                }
            }
        }
        
    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return {
            "healthy": False,
            "error": str(e),
            "timestamp": datetime.utcnow().isoformat()
        }


@router.get("/performance", summary="性能监控报告")
async def get_performance_report(
    admin_user: User = Depends(require_admin_access),
    hours: int = Query(24, description="统计时间范围（小时）"),
) -> Dict[str, Any]:
    """
    获取系统性能监控报告
    
    Args:
        hours: 统计时间范围
        
    Returns:
        Dict[str, Any]: 性能报告
    """
    try:
        report = performance_monitor.generate_performance_report()
        
        # 添加时间范围信息
        report["time_range_hours"] = hours
        report["generated_by"] = str(admin_user.id)
        
        logger.info(f"性能报告生成", admin_user_id=str(admin_user.id))
        return report
        
    except Exception as e:
        logger.error(f"性能报告生成失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="性能报告生成失败"
        )


@router.get("/cache", summary="缓存状态监控")
async def get_cache_status(
    admin_user: User = Depends(require_admin_access)
) -> Dict[str, Any]:
    """
    获取缓存系统状态
    
    Returns:
        Dict[str, Any]: 缓存状态信息
    """
    try:
        # 缓存健康检查
        health_check = await cache_health_check()
        
        # 缓存统计信息
        cache_stats = await cache_manager.get_stats()
        
        return {
            "timestamp": datetime.utcnow().isoformat(),
            "health": health_check,
            "statistics": cache_stats,
            "configuration": {
                "prefix": f"cache_prefix配置信息",
                "default_ttl": 300,
            }
        }
        
    except Exception as e:
        logger.error(f"缓存状态获取失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="缓存状态获取失败"
        )


@router.get("/database", summary="数据库性能分析")
async def get_database_analysis(
    admin_user: User = Depends(require_admin_access),
    session=Depends(get_db),
) -> Dict[str, Any]:
    """
    获取数据库性能分析报告
    
    Returns:
        Dict[str, Any]: 数据库分析报告
    """
    try:
        # 查询优化器报告
        query_report = query_optimizer.get_query_report()
        
        # 数据库整体性能分析
        db_performance = await analyze_database_performance(session)
        
        return {
            "timestamp": datetime.utcnow().isoformat(),
            "query_optimization": query_report,
            "performance_analysis": db_performance,
            "generated_by": str(admin_user.id)
        }
        
    except Exception as e:
        logger.error(f"数据库分析失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="数据库分析失败"
        )


@router.get("/quota", summary="API配额使用情况")
async def get_quota_usage(
    current_user: User = Depends(get_current_user),
    global_stats: bool = Query(False, description="是否获取全局统计"),
) -> Dict[str, Any]:
    """
    获取YouTube API配额使用情况
    
    Args:
        global_stats: 是否获取全局统计（需要管理员权限）
        
    Returns:
        Dict[str, Any]: 配额使用统计
    """
    try:
        # 检查管理员权限（如果请求全局统计）
        if global_stats:
            require_admin_access(current_user)
            user_id = None  # 获取全局统计
        else:
            user_id = str(current_user.id)
        
        quota_stats = await youtube_quota_manager.get_quota_stats(user_id)
        
        return {
            "timestamp": datetime.utcnow().isoformat(),
            "quota_statistics": quota_stats,
            "user_id": user_id,
            "scope": "global" if global_stats else "user"
        }
        
    except Exception as e:
        logger.error(f"配额统计获取失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="配额统计获取失败"
        )


@router.get("/api-stats", summary="API使用统计")
async def get_api_statistics(
    admin_user: User = Depends(require_admin_access),
    hours: int = Query(24, description="统计时间范围（小时）"),
    endpoint: Optional[str] = Query(None, description="特定端点筛选"),
) -> Dict[str, Any]:
    """
    获取API使用统计
    
    Args:
        hours: 统计时间范围
        endpoint: 特定端点筛选
        
    Returns:
        Dict[str, Any]: API统计信息
    """
    try:
        api_stats = performance_monitor.get_api_stats(endpoint, hours)
        
        return {
            "timestamp": datetime.utcnow().isoformat(),
            "time_range_hours": hours,
            "endpoint_filter": endpoint,
            "statistics": api_stats,
            "generated_by": str(admin_user.id)
        }
        
    except Exception as e:
        logger.error(f"API统计获取失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="API统计获取失败"
        )


@router.get("/slow-queries", summary="慢查询分析")
async def get_slow_queries(
    admin_user: User = Depends(require_admin_access),
    limit: int = Query(20, description="返回记录数量"),
) -> Dict[str, Any]:
    """
    获取慢查询分析
    
    Args:
        limit: 返回记录数量
        
    Returns:
        Dict[str, Any]: 慢查询分析结果
    """
    try:
        slow_queries = performance_monitor.get_slow_queries(limit)
        
        return {
            "timestamp": datetime.utcnow().isoformat(),
            "slow_queries": slow_queries,
            "count": len(slow_queries),
            "generated_by": str(admin_user.id)
        }
        
    except Exception as e:
        logger.error(f"慢查询分析失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="慢查询分析失败"
        )


@router.post("/cache/clear", summary="清空缓存")
async def clear_cache(
    admin_user: User = Depends(require_admin_access),
    pattern: Optional[str] = Query("*", description="缓存键模式"),
) -> Dict[str, str]:
    """
    清空缓存
    
    Args:
        pattern: 缓存键模式
        
    Returns:
        Dict[str, str]: 清空结果
    """
    try:
        deleted_count = await cache_manager.delete_pattern(f"*{pattern}*")
        
        logger.warning(f"缓存清空", pattern=pattern, count=deleted_count, admin_user_id=str(admin_user.id))
        
        return {
            "message": f"缓存清空完成",
            "pattern": pattern,
            "deleted_count": deleted_count
        }
        
    except Exception as e:
        logger.error(f"缓存清空失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="缓存清空失败"
        )


@router.get("/memory", summary="内存使用分析")
async def get_memory_analysis(
    admin_user: User = Depends(require_admin_access)
) -> Dict[str, Any]:
    """
    获取内存使用分析
    
    Returns:
        Dict[str, Any]: 内存分析结果
    """
    try:
        memory_usage = MemoryProfiler.get_memory_usage()
        memory_alert = MemoryProfiler.memory_alert_check()
        
        return {
            "timestamp": datetime.utcnow().isoformat(),
            "memory_usage": memory_usage,
            "has_alerts": memory_alert,
            "generated_by": str(admin_user.id)
        }
        
    except Exception as e:
        logger.error(f"内存分析失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="内存分析失败"
        )